import React, { useState, useEffect } from 'react';
import request from '../../../http';
import moment from 'moment';
import { Input, Image, Upload, Descriptions, Modal } from 'antd';
import { DatePicker, Space, Divider } from 'antd';
import { Select } from 'antd';
import { Button, Menu, Dropdown, Form, Radio } from 'antd';
const { RangePicker } = DatePicker;
import { Table } from 'antd';
const { Option } = Select;
import { history } from 'umi';
import { EditorState, convertToRaw } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import draftToMarkdown from 'draftjs-to-markdown'; //获取编辑框得内容
import '../work/index.css';
// 冯小建--作业管理

// 表单布局
const formItemLayout = {
  labelCol: {
    // xs: { span: 24 },
    // sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};

//顶部选择按钮初始状态
const btnStatus = [1, 0, 0];

const Work = () => {
  const [form] = Form.useForm();
  // 表单查询提交
  const [submitForm, setSubmitForm] = useState();
  // 顶部选择按钮
  const [btnStyle, setBtnStyle] = useState(btnStatus);
  //作业任务信息
  const [workInfo, setWorkInfo] = useState(btnStatus);
  // 作业答案
  const [answerInfo, setAnswerInfo] = useState();
  // 作业分数信息
  const [scoreInfo, setScoreInfo] = useState({
    comment: null,
    score: -1,
  });
  // 富文本内容
  const [editorState, setEditorState] = useState();
  const [editorContent, setEditorContent] = useState();
  // 传值作业id、类型
  const [workIdInfo, setWorkId] = useState(0);
  const [workType, setWorkType] = useState(0);

  // 顶部状态选择变化
  const changeTableInfo = (type) => {
    switch (type) {
      case 0:
        setBtnStyle([1, 0, 0]);
        break;
      case 1:
        setBtnStyle([0, 1, 0]);
        workType === 2 && getAnswerInfo(workIdInfo);
        break;
      case 2:
        setBtnStyle([0, 0, 1]);
        break;
    }
  };

  // 作业信息任务接口
  const getWorkInfo = (workId) => {
    console.log('执行-作业信息任务接口');
    request
      .post('/homeworksec/t_s/showHomeworkInfo', {
        workId: workId,
      })
      .then((response) => {
        // 判断
        if (response.code === 20000) {
          // 成功
          console.log(response.data);
          response.data && setWorkInfo(response.data); //设置
        } else {
          // alert(response.message);
          console.log(response.message);
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };

  // 获取回答答案
  const getAnswerInfo = (workId) => {
    console.log('执行-答案接口');
    request
      .post('/homeworksec/student/showHomeworkAnswerStudent', {
        sumbitId: workId,
      })
      .then((response) => {
        // 判断
        if (response.code === 20000) {
          // 成功
          console.log('答案', response.data);
          response.data && setAnswerInfo(response.data); //设置
        } else {
          // alert(response.message);
          console.log(response.message);
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };

  // 获取作业得分
  const getScore = (workId) => {
    console.log('执行-分数接口');
    request
      .post('/homeworksec/student/showHomeworkScoreStudent', {
        sumbitId: workId,
      })
      .then((response) => {
        // 判断
        if (response.code === 20000) {
          // 成功
          console.log('分数', response.data);
          response.data && setScoreInfo(response.data); //设置
        } else {
          alert(response.message);
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };

  // 上传附件
  const normFile = (e: any) => {
    console.log('Upload event:', e);
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  // 富文本变化
  const onEditorStateChange = (editorState) => {
    // console.log(convertToRaw(editorState.getCurrentContent()))
    setEditorState(editorState);
  };
  //获取内容变化值
  const onEditorChange = (editorContent) => {
    // console.log(JSON.stringify(editorContent));
    setEditorContent(editorContent);
  };

  // 重置
  const onReset = () => {
    form.resetFields();
  };

  //提交作业
  const onFinish = (fieldsValue: any) => {
    // 转换富文本信息
    const editorContent = draftToMarkdown(
      convertToRaw(editorState.getCurrentContent()),
    );
    const submitTime = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss') || ''; //当前时间
    const values = {
      // ...fieldsValue,
      answerContent: editorContent,
      submitId: workIdInfo,
      // "submitTime":submitTime
    };
    setSubmitForm(values);
    values && showModal();
    console.log('Received values of form: ', fieldsValue, values);
  };

  // 初加载
  useEffect(() => {
    const { query = {} } = history.location;
    console.log('获取的wokid', query.submitId, 'workType:', query.statuType);
    setWorkId(parseInt(query.submitId));
    setWorkType(parseInt(query.statuType));
    // 获取初始值
    getWorkInfo(parseInt(query.submitId));
    getScore(parseInt(query.submitId));
  }, []);

  const [visible, setVisible] = React.useState(false);
  const [confirmLoading, setConfirmLoading] = React.useState(false);
  const [modalText, setModalText] = React.useState('确定要提交吗？');

  const showModal = () => {
    setVisible(true);
  };

  const handleOk = () => {
    setModalText('正在提交...');
    setConfirmLoading(true);
    setTimeout(() => {
      setVisible(false);
      setConfirmLoading(false);
      // 执行发布作业
      request
        .post('/homeworksec/student/addHomeworkAnswer', submitForm)
        .then((response) => {
          console.log(response);
          // 判断
          if (response.code === 20000) {
            console.log('提交作业成功');
            Modal.success({
              content: '提交作业成功！',
            });
            history.push('/student/work/correct');
          } else {
            // alert(response.message);
            Modal.error({
              title: '失败',
              content: response.message,
            });
          }
        })
        .catch((error) => {
          console.log(error);
          Modal.error({
            title: '失败',
            content: '提交失败',
          });
        });
    }, 2000);
  };

  const handleCancel = () => {
    console.log('Clicked cancel button');
    setVisible(false);
  };

  return (
    <div>
      {/* 顶部选择按钮 */}
      <div className="btn-box">
        <Button
          className={btnStyle[0] === 1 ? 'isPointed' : 'noPointed'}
          onClick={changeTableInfo.bind(this, 0)}
          size="large"
        >
          作业任务
        </Button>
        <Button
          className={btnStyle[1] === 1 ? 'isPointed' : 'noPointed'}
          onClick={changeTableInfo.bind(this, 1)}
          size="large"
        >
          学生答题
        </Button>
        <Button
          className={btnStyle[2] === 1 ? 'isPointed' : 'noPointed'}
          onClick={changeTableInfo.bind(this, 2)}
          size="large"
        >
          老师批复
        </Button>
      </div>

      {/* 作业任务 */}
      {btnStyle[0] === 1 ? (
        <div className="part">
          <div className="workContent">
            <h1>{workInfo.workTheme}</h1>
            <p>{workInfo.workContent}</p>
            {/* <Image
            width={200}
            height={200}
            src="erro"
            fallback=""
          /> */}
            {/* 相关附件 */}
            {workInfo.annexId ? (
              <div>
                <Divider />
                <h3>附件:</h3>
              </div>
            ) : null}
          </div>

          <Descriptions title="" bordered>
            <Descriptions.Item label="发布人">
              {workInfo.userName}
            </Descriptions.Item>
            <Descriptions.Item label="发布时间">
              {workInfo.releaseDateTime}
            </Descriptions.Item>
            <Descriptions.Item label="计划时间">
              {workInfo.completionDateTime}
            </Descriptions.Item>
          </Descriptions>
        </div>
      ) : null}

      {/* 学生答题 */}
      {btnStyle[1] === 1 ? (
        <div className="part">
          {workType === 1 ? (
            <Form onFinish={onFinish} form={form}>
              {/* 上传附件 */}
              <Form.Item
                name="upload"
                label="相关附件"
                valuePropName="fileList"
                getValueFromEvent={normFile}
              >
                <Upload name="logo" action="/upload.do" listType="picture">
                  <Button className="ant-btn ant-btn-primary addLeave">
                    上传附件
                  </Button>
                </Upload>
              </Form.Item>

              {/* 富文本 */}
              <Form.Item name="answerContent">
                <div>
                  <Editor
                    // editorState={editorState}
                    wrapperClassName="demo-wrapper"
                    editorClassName="demo-editor"
                    editorState={editorState}
                    onContentStateChange={onEditorChange} //获取内容变化值
                    onEditorStateChange={onEditorStateChange} //编辑器状态发生变化时
                    // onEditorStateChange={this.onEditorStateChange}
                  />
                  {/* <textarea
                    disabled
                  // value={draftToHtml(convertToRaw(editorState.getCurrentContent()))}
                  /> */}
                </div>
              </Form.Item>

              {/* 按钮 */}
              <Form.Item>
                <Button type="primary" htmlType="submit">
                  确认提交
                </Button>
                <Modal
                  title="提交作业"
                  visible={visible}
                  onOk={handleOk}
                  confirmLoading={confirmLoading}
                  onCancel={handleCancel}
                >
                  <p>{modalText}</p>
                </Modal>
                <Button htmlType="button" style={{ marginLeft: '10px' }}>
                  保存草稿
                </Button>
              </Form.Item>
            </Form>
          ) : (
            <h3>作业已提交，你无法查看答案</h3>
          )}
        </div>
      ) : null}

      {/* 老师批复 */}
      {btnStyle[2] === 1 ? (
        <div className="part">
          {workType === 2 ? (
            <div>
              <div className="teacherBack">
                得分：
                <span className="score">
                  {scoreInfo.score === -1 ? '' : scoreInfo.score}
                </span>
              </div>
              <div className="teacherBack">附件：</div>
              <div className="teacherBack">
                评语：{scoreInfo.comment ? scoreInfo.comment : '暂无评语'}
              </div>
            </div>
          ) : (
            <h3>暂无评分</h3>
          )}
        </div>
      ) : null}
    </div>
  );
};
export default Work;
